package com.shinhye.smartsms;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.shinhye.smartsms.utils.CommonUtils;
import com.shinhye.smartsms.utils.MyAsyncQueryHandler;
import com.shinhye.smartsms.utils.MyAsyncQueryHandler.OnChangeCursorListener;

public class FolderDetailActivity extends Activity implements OnClickListener, OnChangeCursorListener{
	private int type;
	private MyAdapter adapter;
	private List<Map<String, Object>> datalist;
	private MyAsyncQueryHandler asyncQueryHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_folder_detail);
		Intent intent = getIntent();
		type = intent.getIntExtra("type", -1);
		
		initTitle();
		
		ListView lv_smss = (ListView) findViewById(R.id.lv_smss);
		Button btn_newsms = (Button) findViewById(R.id.btn_newsms);
		
		datalist = new ArrayList<Map<String, Object>>();
		adapter = new MyAdapter(this, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		lv_smss.setAdapter(adapter);
		btn_newsms.setOnClickListener(this);
		
		asyncQueryHandler = new MyAsyncQueryHandler(getContentResolver());
		asyncQueryHandler.setOnChangeCursorListener(this);
		getData();
	}
	
	private void initTitle() {
		switch(type) {
		case 0:
			setTitle("收件箱");
			break;
		case 1:
			setTitle("发件箱");
			break;
		case 2:
			setTitle("已发送");
			break;
		case 3:
			setTitle("草稿箱");
			break;
		}
	}

	private void getData() {
		asyncQueryHandler.startQuery(119, adapter, CommonUtils.getUri(type), new String[]{"_id", "address", "body", "date"}, null, null, "date desc");
	}

	class MyAdapter extends CursorAdapter {
		public MyAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
		}
		
		@Override
		protected void onContentChanged() {
			datalist.clear();
			getData();
		}
		
		@Override
		public int getCount() {
			return datalist.size();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Map<String, Object> map = datalist.get(position);
			System.out.println(position + "::" + map.values());
			if(map.containsKey("date")) {
				TextView view = new TextView(FolderDetailActivity.this);
				long date = (Long) map.get("date");
				String dateStr = DateFormat.getDateFormat(FolderDetailActivity.this).format(date);
				view.setText(dateStr);
				view.setBackgroundColor(Color.CYAN);
				view.setTextSize(18);
				view.setGravity(Gravity.CENTER_HORIZONTAL);
				return view;
			}
			
			Cursor cursor = getCursor();
			cursor.moveToPosition((Integer) map.get("sms"));
	        View v;
	        if (convertView == null || convertView instanceof TextView) {
	            v = newView(FolderDetailActivity.this, cursor, parent);
	        } else {
	            v = convertView;
	        }
	        bindView(v, FolderDetailActivity.this, cursor);
	        return v;
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View view = View.inflate(context, R.layout.item_conversation, null);
			ViewHolder holder = new ViewHolder();
			
			holder.iv_contact = (ImageView) view.findViewById(R.id.iv_contact);
			holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
			holder.tv_msg = (TextView) view.findViewById(R.id.tv_msg);
			holder.tv_date = (TextView) view.findViewById(R.id.tv_date);
			view.setTag(holder);
			return view;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewHolder holder = (ViewHolder) view.getTag();
			String address = cursor.getString(1);
			String body = cursor.getString(2);
			long date = cursor.getLong(3);
			
			String contactName = CommonUtils.getContactName(getContentResolver(), address);
			if(TextUtils.isEmpty(contactName)) {
				holder.tv_name.setText(address);
				holder.iv_contact.setImageResource(R.drawable.ic_unknow_contact_picture);
			} else {
				holder.tv_name.setText(contactName);
				Bitmap photo = CommonUtils.getContactPhoto(getContentResolver(), address);
				if(photo == null)
					holder.iv_contact.setImageResource(R.drawable.ic_contact_picture);
				else
					holder.iv_contact.setImageBitmap(photo);
			}
			
			holder.tv_msg.setText(body);
			
			String formattedDate;
			if(DateUtils.isToday(date)) {
				formattedDate = DateFormat.getTimeFormat(context).format(new Date(date));
			} else {
				formattedDate = DateFormat.getDateFormat(context).format(new Date(date));
			}
			holder.tv_date.setText(formattedDate);
		}
	}

	class ViewHolder {
		ImageView iv_contact;
		TextView tv_name;
		TextView tv_msg;
		TextView tv_date;
	}
	
	@Override
	public void onClick(View v) {
		Intent intent = new Intent(this, CreateSMSActivity.class);
		startActivity(intent);
	}

	@Override
	public void preFunc(int token, Object cookie, Cursor cursor) {
		String curDate = null;
		cursor.moveToPosition(-1);
		while(cursor.moveToNext()) {
			Map<String, Object> map = new HashMap<String, Object>();
			long date = cursor.getLong(3);
			String dateStr = DateFormat.getDateFormat(this).format(date);
			if(!dateStr.equals(curDate)) {
				map.put("date", date);
				curDate = dateStr;
				datalist.add(map);
				map = new HashMap<String, Object>();
			}
			map.put("sms", cursor.getPosition());
			datalist.add(map);
		}
		System.out.println(datalist);
	}

	@Override
	public void afterFunc(int token, Object cookie, Cursor cursor) {
	}
}
